package pri.zey.custom.tools.http;

import android.content.Context;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Iterator;

import pri.zey.custom.tools.TLog;
import pri.zey.custom.tools.TStrKit;

/**
 * Created by Administrator on 2016/3/9.
 *
 */
public class ZHttpService<T> extends ZHttpAgency {

    public ZHttpService(Context mContext, String mMethod, Object mObject, int mRequestMethod) {
        this.mContext = mContext;
        this.mMethod = mMethod;
        this.mObject = mObject;
        this.mRequestMethod = mRequestMethod;
    }

    public ZHttpService(Context mContext, String mMethod, Object mObject, int mRequestMethod, RequestSuccess mSuccess) {
        this.mContext = mContext;
        this.mMethod = mMethod;
        this.mObject = mObject;
        this.mRequestMethod = mRequestMethod;
        this.mSuccess = mSuccess;
    }

    public ZHttpService(Context mContext, String mMethod, Object mObject, int mRequestMethod, RequestSuccess mSuccess, RequestFail mFail) {
        this.mContext = mContext;
        this.mMethod = mMethod;
        this.mObject = mObject;
        this.mRequestMethod = mRequestMethod;
        this.mSuccess = mSuccess;
        this.mFail = mFail;
    }

    @Override
    public void setOutBuffer() {
        JSONObject jsonObject = (JSONObject) mObject;
        if(jsonObject != null){
            Iterator mIterator = jsonObject.keys();
            while(mIterator.hasNext()){
                try {
                    String name = mIterator.next().toString();
                    String value = jsonObject.getString(name);
                    mOutBuffer.append(name).append("=")
                            .append(value).append("&");
                } catch (JSONException e) {
                    if(mContext != null)
                        //mContext.sendBroadcast(new Intent().setAction(TLog.ACTION_Msg_Toasts).putExtra("msg", "网络异常"));
                    TLog.Log(mMethod + " Error JSONException==============> \n" + e.toString(), TLog.LOG_E);
                }
            }
        }
        TLog.Log("你发送的参数：" + mOutBuffer.toString());
    }

    @Override
    public void setConnectionConfig() {
        try {
            mConnection.setDoInput(true);
            mConnection.setDoOutput(true);
            mConnection.setConnectTimeout(TimeOut);
            mConnection.setRequestProperty("accept", "*/*");
            mConnection.setRequestProperty("connection", "Keep-Alive");
            mConnection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setConnectionType() {
        try {
            mPrintWriter = new PrintWriter(mConnection.getOutputStream());
            mPrintWriter.write(mOutBuffer.toString());
            mPrintWriter.flush();
        } catch (IOException e) {
            if(mContext != null) {
//                mContext.sendBroadcast(new Intent().setAction(TLog.ACTION_Msg_Toasts).putExtra("msg", "网络异常"));
            }
            TLog.Log(mMethod + " Error IOException==============> \n" + e.toString(), TLog.LOG_E);
        }
    }

    @Override
    public JSONObject setReaderBuffer() {
        JSONObject jObject = null;
        try {
            mReaderBuffer = new BufferedReader(new InputStreamReader(mConnection.getInputStream()));
            String strResponse = "";
            while ((strResponse = mReaderBuffer.readLine()) != null){
                mInputBuffer.append(strResponse);
            }
            jObject = new JSONObject(mInputBuffer.toString());
            TLog.Log("接收到的参数：" + jObject.toString());
            RequestValues jStr = new RequestValues();
            jStr.x_id = jObject.getString("x-id").trim();
            jStr.x_value = jObject.getString("x-value").trim();
            jStr.x_msg = jObject.getString("x-msg").trim();
            jStr.x_sign = jObject.getString("x-sign").trim();
            jStr.x_return = jObject.getString("x-return").trim();
            jStr.x_url = jObject.getString("x-url").trim();
            jStr.x_timestamp = jObject.getString("x-timestamp").trim();
            if(true){
                if(TStrKit.isBlank(jStr.x_return) && jStr.x_return.equals("0")){
                    if(mSuccess != null){
                        String valueStr = jStr.x_value.toString().trim();
                        mSuccess.onSuccess(mMethod, jStr);
                        TLog.Log("value ：" + valueStr.toString());
                    }else{
                        if(mFail != null){
                            mFail.onFail(mMethod, jStr);
                        }
                        TLog.Log(mMethod + " Error ==============> 3 Have a Error", TLog.LOG_E);
                        if(mContext != null){
//                            mContext.sendBroadcast(new Intent().setAction(.ACTION_Msg_Toasts).putExtra("msg", "mSuccess is null"));
                        }
                    }
                }else{
                    if(mFail != null){
                        mFail.onFail(mMethod, jStr);
                    }
                    TLog.Log(mMethod + " Error ==============> 2 Have a Error", TLog.LOG_E);
                    if(mContext != null) {
//                        mContext.sendBroadcast(new Intent().setAction(TLog.ACTION_Msg_Toasts).putExtra("msg", jStr.x_msg));
                    }
                }
            }else{
                if(mFail != null){
                    mFail.onFail(mMethod, jStr);
                }
                TLog.Log(mMethod + " Error ==============> 1 Have a Error", TLog.LOG_E);
                if(mContext != null) {
//                    mContext.sendBroadcast(new Intent().setAction(TLog.ACTION_Msg_Toasts).putExtra("msg", "与本地签名冲突:" + jStr.x_msg));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }finally {
            return jObject;
        }
    }

    @Override
    public void closeObject() {
        try {
            if(mReaderBuffer != null){
                mReaderBuffer.close();
            }
            if(mPrintWriter != null){
                mPrintWriter.close();
            }
            if(mConnection != null){
                mConnection.disconnect();
            }
        } catch (IOException e) {
            TLog.Log(mMethod + " Error finally-IOException==============> \n" + e.toString(), TLog.LOG_E);
        }
    }

    @Override
    public void run() {
        super.run();
        TLog.Log("************************ execute START ************************", TLog.LOG_E);
        try {
            URL url;
            if(TStrKit.notBlank(this.PrimaryDomain))
                url = new URL(this.PrimaryDomain + "/" + mMethod);
            else if(TStrKit.notBlank(this.DeputyDomain))
                url = new URL(this.DeputyDomain + "/" + mMethod);
            else{
                return ;
            }
            TLog.Log("************************ url: " + url.toString(), TLog.LOG_E);
            mConnection = (HttpURLConnection) url.openConnection();
            TLog.Log("************************ setOutBuffer ************************", TLog.LOG_E);
            setOutBuffer();
            TLog.Log("************************ setConnectionConfig ************************", TLog.LOG_E);
            setConnectionConfig();
            TLog.Log("************************ setReaderBuffer ************************", TLog.LOG_E);
            setReaderBuffer();
        }  catch (Exception e) {
            TLog.Log("Error IOException==============> \n" + e.toString(), TLog.LOG_E);
            TLog.Log("mMethod : " + mMethod, TLog.LOG_E);
        } finally{
            TLog.Log("************************ execute END *************************", TLog.LOG_E);
            closeObject();
        }
    }


}
